<template>
  <div class="monitor-box">
    <headNav title="查看监控"></headNav>
    <div class="dv-title">{{device.monitorName}}</div>
    <div class="video-box" id="videobox" v-show="isShowVideo">
      <video-player ref="videoPlayer" class="video-player vjs-custom-skin" :playsinline="true" :options="playerOptions" />
    </div>
   
    <div v-show="isLoading" class="loading-div">加载中({{loadingTime}})...</div>
    <!-- <div class="dv-title">心跳：{{beatCount}}</div> -->
  </div>
</template>
<script>
import { mapState, mapGetters } from 'vuex'
import headNav from '@/components/headNav/headNav'
import {beat} from '@/api/monitorApi'
import {wsUrl} from '@/config/config'


// 播放m3u8的插件使用
import Vue from 'vue'
import VideoPlayer from 'vue-video-player'
require('video.js/dist/video-js.css')
require('vue-video-player/src/custom-theme.css')
Vue.use(VideoPlayer)
const hls = require('videojs-contrib-hls')
Vue.use(hls)

export default {
  // name: 'watchMonitor',
  components: {
    headNav
  },
  computed: {
       
        schoolName () {
            return this.$store.state.user.schoolName
        }
    },
  data () {
    return {
      beatCount: 0,
      isLoading: true,
      loadingTime: 0,
      isShowVideo: false,
      schoolId: '',
      isBeat: true,
      beatInterval: 20000,
      device: {},
      monitorUrl: '',
      playerOptions: {
        // playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, // 如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: 'application/x-mpegURL', // 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
            src: '' // url地址
          }
        ],
        hls: true,
        width: document.documentElement.clientWidth, // 播放器宽度
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true // 全屏按钮
        }
      },
    }
  },
  methods: {
      player () {
        return this.$refs.videoPlayer.player//自定义播放
        },
        beat () {
          
          beat({
            school_id: this.schoolId,
            device_id: this.device.monitorCode
          }).then(res => {
            this.beatCount ++
              if (this.isBeat) {
                   setTimeout(() => {
                      this.beat()
                    }, this.beatInterval)
              }
          })
        },
      init () {
        console.log('init...........')
      

       this.interval = setInterval(() => {
         this.loadingTime ++
       }, 1000)
       
       this.timer = setTimeout(() => {
            if (!this.isShowVideo) {
               this.isLoading = false
               clearInterval(this.timer)
                 this.$vux.alert.show({
                      content: '视频加载失败',
                      maskZIndex: 100,
                      onHide () {
                        
                      }
                  })
            }
        }, 10000)
        
          this.device =  this.$store.state.monitor.device
          this.schoolId = this.$store.state.user.schoolId

          // this.schoolId = '152707f8352960200b7039f779cb03bd'
          // this.device.monitorCode = '6a3a0180d3004ddfb6d50a7f5ab87ba9'

          var ws = new WebSocket(wsUrl + "/video-streaming?schoolId=" + this.schoolId + "&deviceId=" + this.device.monitorId)
          this.ws = ws
            ws.onopen = () => {
            　　//当WebSocket创建成功时，触发onopen事件
                console.log("open");
            　　ws.send("hello"); //将消息发送到服务端
                
            }
            ws.onmessage = (e) => {
            　　//当客户端收到服务端发来的消息时，触发onmessage事件，参数e.data包含server传递过来的数据
            　　console.log(e.data);
              this.playerOptions.sources[0].src = e.data
              this.isShowVideo = true
               this.isLoading = false
               clearInterval(this.timer)
               this.beat()
            }
            ws.onclose = function(e){
            　　//当客户端收到服务端发送的关闭连接请求时，触发onclose事件
            　　console.log("close");
            }
            ws.onerror = function(error){
               alert('websocket链接错误')
            　　//如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
            　　console.log(error);
            }
      }
  },
  mounted () {
    // this.playerOptions.sources[0].src = this.$route.query.monitorUrl
     this.init()
  },
  destroyed () {
    console.log('look destroy...')
    this.isBeat = false
    this.isShowVideo = true
    this.ws.close()

    clearInterval(this.interval)
    clearTimeout(this.timer)
  }
}
</script>
<style scoped>
/* .video-box {
  width: 100%;
  height: 400px;
  background-color: pink;
} */
.dv-title{
  padding: 0.2rem 0.4rem;
}
.loading-div{
  text-align: center; padding: 1rem 0;
}
</style>
